package com.zyj.springboot.validators;

import com.zyj.springboot.dto.UserDto;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * @author : zhouyajun
 * @date : 2020-05-14
 */
public class PasswordValidator implements ConstraintValidator<PasswordEqual, UserDto> {
    private int min;
    private int max;

    /**
     * 通过下面这个方法可以获取到注解的参数
     *
     * @param constraintAnnotation
     */
    @Override
    public void initialize(PasswordEqual constraintAnnotation) {
        this.min = constraintAnnotation.min();
        this.max = constraintAnnotation.max();
    }

    @Override
    public boolean isValid(UserDto userDto, ConstraintValidatorContext constraintValidatorContext) {
        if (userDto.getPassword() != null && userDto.getConfirmPassword() != null) {
            if (checkPassword(userDto.getPassword()) &&
                    checkPassword(userDto.getConfirmPassword())) {
                return userDto.getPassword().equals(userDto.getConfirmPassword());
            }
        }
        return false;
    }


    private boolean checkPassword(String password) {
        return password.length() >= min && password.length() <= max;
    }
}
